package me.dwliu.springcloud.ch1802gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

public class CustomerGatewayFilter implements GatewayFilter, Ordered {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerGatewayFilter.class);

    private static final String COUNT_START_TIME = "countStartTime";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(COUNT_START_TIME, System.currentTimeMillis());

        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    Long startTime = exchange.getAttribute(COUNT_START_TIME);

                    Long endTime = System.currentTimeMillis() - startTime;
                    if (startTime != null) {
                        LOGGER.info(exchange.getRequest().getURI().getRawPath() + "," + endTime + "ms");
                    }

                })
        );

    }

    @Override
    public int getOrder() {
        //return Ordered.LOWEST_PRECEDENCE;
        return 0;
    }
}
